package com.climb.ssm.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Administrator
 */
public class BeanFactory3 {
    private static Properties properties = new Properties();
    // Bean缓存
    private static Map<String, Object> cache = new HashMap<>();

    static {
        try {
            InputStream resourceAsStream = BeanFactory3.class.getResourceAsStream("/bean.properties");
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> T getBean(String beanName, Class<T> ifaceClass) {
        // 判断缓存中是否已有对象
        if(cache.containsKey(beanName)) {
            return (T)cache.get(beanName);
        }

        // asSubclass用于指定Class.forName()创建对象的具体类型accountService--->accountServiceImpl
        T t = null;
        try {
            String className = properties.getProperty(beanName);
            /*asSubclass子类化*/
            t = Class.forName(className).asSubclass(ifaceClass).getDeclaredConstructor().newInstance();
            cache.put(beanName, t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }
}
